package com.orange.off.cloud.cloudoff.fragments;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.orange.off.cloud.cloudoff.R;
import com.orange.off.cloud.cloudoff.activity.IntermediaryActivity;
import com.orange.off.cloud.cloudoff.app.MyApplication;
import com.orange.off.cloud.cloudoff.events.ChangePasswordEvent;
import com.orange.off.cloud.cloudoff.events.PersonalUpdateInformationEvent;
import com.orange.off.cloud.cloudoff.model.UploadResponse;
import com.orange.off.cloud.cloudoff.urls.AppUrls;
import com.orange.off.cloud.cloudoff.utils.JsonUtils;
import com.orange.off.cloud.cloudoff.utils.Options;
import com.orange.off.cloud.cloudoff.utils.ProgressDlgUtil;
import com.orange.off.cloud.cloudoff.utils.SPUtil;
import com.orange.off.cloud.cloudoff.utils.ToastUtils;
import com.orange.off.cloud.cloudoff.views.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

/**
 * 个人中心
 *
 * @author smile
 */
public class PersonalFragment extends Fragment {
    @Bind(R.id.img_avatar)
    CircleImageView imgAvatar;
    @Bind(R.id.tv_username)
    TextView tvUsername;
    @Bind(R.id.rlt_into_personal_center)
    RelativeLayout rltIntoPersonalCenter;
    @Bind(R.id.rlt_myNotice)
    RelativeLayout rltMyNotice;
    @Bind(R.id.rlt_myCommission)
    RelativeLayout rltMyCommission;
    @Bind(R.id.rlt_myMuthentication)
    RelativeLayout rltMyMuthentication;
    @Bind(R.id.rlt_myAboutus)
    RelativeLayout rltMyAboutus;
    @Bind(R.id.tvBtn_exit)
    TextView tvBtnExit;
    private DisplayImageOptions options;
    private String headerPic = "";
    private String personalName = "";
    private String personalPhone = "";

    public static PersonalFragment newInstance() {
        PersonalFragment fragment = new PersonalFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        initViews();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.personal_fragment, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    private void initViews() {
        options = Options.getHeaderOptions();
        getInformation();
    }

    /**
     * EventBus：信息修改成功事件通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onInformationUpdateEvent(PersonalUpdateInformationEvent event) {
        if (event.success) {
            getInformation();
        }
    }

    /**
     * 获取个人信息
     */
    void getInformation() {
        ProgressDlgUtil.showProgressDlg("数据获取中,请稍后...", getActivity());
        RequestParams params = new RequestParams();
        params.addFormDataPart("aid", MyApplication.aid);
        HttpRequest.post(AppUrls.GetInformation, params, new BaseHttpRequestCallback<UploadResponse>() {
            @Override
            public void onSuccess(UploadResponse uploadResponse) {
                super.onSuccess(uploadResponse);
                ProgressDlgUtil.stopProgressDlg();
                Log.d(MyApplication.DEBUG, "personal--success-》" + uploadResponse.toString());

                if (uploadResponse.getSuccess()) {
                    try {
                        JSONObject jsonObject = new JSONObject(uploadResponse.getData());
                        headerPic = JsonUtils.getString(jsonObject, "image", "");
                        personalName = JsonUtils.getString(jsonObject, "name", "");
                        personalPhone = JsonUtils.getString(jsonObject, "phone", "");
                        ImageLoader.getInstance().displayImage(headerPic, imgAvatar, options);
                        tvUsername.setText(personalName);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                }

            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
                ProgressDlgUtil.stopProgressDlg();
            }

            @Override
            public void onProgress(int progress, long networkSpeed, boolean done) {
            }
        });
    }

    @OnClick({R.id.img_avatar, R.id.rlt_into_personal_center, R.id.rlt_myNotice, R.id.rlt_myCommission, R.id.rlt_myMuthentication
            , R.id.rlt_myAboutus, R.id.tvBtn_exit})
    public void onClick(View view) {
        Intent intent = new Intent(getActivity(), IntermediaryActivity.class);
        switch (view.getId()) {
            case R.id.img_avatar:
                //头像：

                break;
            case R.id.rlt_into_personal_center:
                //个人中心：
                intent.putExtra("type", IntermediaryActivity.MYPROFILE);
                Bundle bundle = new Bundle();
                bundle.putString("headerPic", headerPic);
                bundle.putString("personalName", personalName);
                bundle.putString("personalPhone", personalPhone);
                intent.putExtra("bundle", bundle);
                startActivity(intent);
                break;
            case R.id.rlt_myNotice:
                //我的通知：
                intent.putExtra("type", IntermediaryActivity.NOTICE);
                startActivity(intent);
                break;
            case R.id.rlt_myCommission:
                //我的佣金：
                intent.putExtra("type", IntermediaryActivity.MYCOMMISSION);
                startActivity(intent);
                break;
            case R.id.rlt_myMuthentication:
                //我的认证：
                intent.putExtra("type", IntermediaryActivity.AUTHENTICATION);
                startActivity(intent);
                break;
            case R.id.rlt_myAboutus:
                //关于我们：
                intent.putExtra("type", IntermediaryActivity.ABOUTUS);
                startActivity(intent);
                break;
            case R.id.tvBtn_exit:
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("云客提示");
                builder.setMessage("确定退出账户？");
                builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(), "退出成功", Toast.LENGTH_SHORT).show();
                        SPUtil.remove(getActivity(), "username");
                        SPUtil.remove(getActivity(), "password");
                        EventBus.getDefault().post(new ChangePasswordEvent(true));
                        Intent intent = new Intent(getActivity(), IntermediaryActivity.class);
                        intent.putExtra("type", IntermediaryActivity.LOGIN);
                        startActivity(intent);

                    }
                });
                builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();//展示对话框
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

}
